﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitBase.WinForm;
using YJKRevitDimension.DetailIndex.Forms;
using YJKRevitDimension.DetailIndex.Operate;
using YJKRevitDimensionText.Utility;
using YJKRevitView;

namespace YJKRevitDimension.DetailIndex.Manager
{
	internal class DetailIndexManger
	{
		public DetailIndexManger(ExternalCommandData revit)
		{
			this.m_Revit = revit;
		}

		public Result Create()
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			Autodesk.Revit.DB.View activeView = document.ActiveView;
			CmdViewType types = (CmdViewType)105;
			if (SwitchView.SetUsableView(types, this.m_Revit) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			string text = "";
			if (!Helper.ViewValidating(document, activeView, ref text))
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			this.m_DetailIndexOperator = new NoRangeDetailIndexOperate(this.m_Revit, new DetailIndexParameter());
			IntPtr mainWindowHandle = Process.GetCurrentProcess().MainWindowHandle;
			DetailIndexManger._hWndRevit = new WindowHandle(mainWindowHandle);
			DetailIndexForm detailIndexForm = new DetailIndexForm(mainWindowHandle, this.m_DetailIndexOperator, this.m_Revit);
			detailIndexForm.Show(DetailIndexManger._hWndRevit);
			int wMsg = 7;
			DetailIndexManger.SendMessage(DetailIndexManger._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			for (;;)
			{
				Result result = detailIndexForm.DetailIndexOperate.Operate();
				if (result == Autodesk.Revit.UI.Result.Cancelled && detailIndexForm.IfChanged)
				{
					detailIndexForm.IfChanged = false;
				}
				else
				{
					if (result == null && detailIndexForm.DetailIndexOperate.Finished)
					{
						try
						{
							detailIndexForm.DetailIndexOperate.Create(detailIndexForm.m_DetailIndexPara);
							detailIndexForm.IfChanged = false;
							DetailIndexManger.SendMessage(DetailIndexManger._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
							continue;
						}
						catch
						{
							detailIndexForm.Close();
							goto IL_138;
						}
						break;
					}
					break;
				}
			}
			detailIndexForm.DetailIndexOperate.DeleteTempElement();
			IL_138:
			detailIndexForm.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private static WindowHandle _hWndRevit;

		public IDetailIndexOperate m_DetailIndexOperator;

		private ExternalCommandData m_Revit;
	}
}
